<template>
  <div class="info">
    <div class="box2">
      <el-row>
        <el-col :span="24">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="基本信息" name="first">
              <el-form
                :model="ruleForm"
                status-icon
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item label="一级分类" prop="first_cateid">
                  <el-select v-model="ruleForm.first_cateid" @change="firstChange">
                    <!-- <el-option label="请选择" :value="0"></el-option> -->
                    <el-option
                      v-for="(item,index) in firstCateList"
                      :key="index"
                      :label="item.catename"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="二级分类" prop="second_cateid">
                  <el-select v-model="ruleForm.second_cateid">
                    <!-- <el-option label="请选择" :value="0"></el-option> -->
                    <el-option
                      v-for="(item,index) in secondCateList"
                      :key="index"
                      :label="item.catename"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="goodsname" label="商品名称">
                  <el-input v-model="ruleForm.goodsname"></el-input>
                </el-form-item>
                <el-form-item prop="price" label="商品价格">
                  <el-input v-model="ruleForm.price"></el-input>
                </el-form-item>
                <el-form-item prop="market_price" label="市场价格">
                  <el-input v-model="ruleForm.market_price"></el-input>
                </el-form-item>
                <el-form-item label="分类图片" prop="img">
                  <!-- action 属性： 上传地址！ 如果写了地址，那么选择图片之后就会自动上传！  -->
                  <!-- list-type属性： 上传控件的类型 -->
                  <!-- file-list属性： 文件列表  [{name:'',url:""}] -->
                  <!-- limit属性：上传最大个数 -->
                  <!-- on-change: 图片变了的时候 -->
                  <!-- name属性： 上传的对应字段 -->
                  <!-- auto-upload:是否自动上传 -->
                  <el-upload
                    action="#"
                    list-type="picture-card"
                    :file-list="fileList"
                    :auto-upload="false"
                    :limit="1"
                    :on-change="handleChange"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item label="商品规格" prop="specsid">
                  <el-select v-model="ruleForm.specsid" @change="specIdChange">
                    <!-- <el-option label="请选择" :value="0"></el-option> -->
                    <el-option
                      v-for="(item,index) in goodSpec"
                      :key="index"
                      :label="item.specsname"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="规格属性值" prop="specsattr">
                  <el-select v-model="ruleForm.specsattr" multiple placeholder="请选择">
                    <el-option
                      v-for="(item,index) in goodSpecAttr"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="isnew" label="是否新品">
                  <el-radio v-model="ruleForm.isnew" :label="1">是</el-radio>
                  <el-radio v-model="ruleForm.isnew" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item prop="ishot" label="是否热卖">
                  <el-radio v-model="ruleForm.ishot" :label="1">是</el-radio>
                  <el-radio v-model="ruleForm.ishot" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                  <el-radio v-model="ruleForm.status" :label="1">正常</el-radio>
                  <el-radio v-model="ruleForm.status" :label="2">禁用</el-radio>
                </el-form-item>
                <el-form-item>
                  <el-button v-if="popType=='修改'" type="danger" @click="submitForm('ruleForm')">立即修改</el-button>
                  <el-button v-else type="success" @click="submitForm('ruleForm')">立即添加</el-button>
                  <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="详细描述" name="second">
              <div id="editor"></div>
              <el-button v-if="popType=='修改'" type="danger" @click="submitForm('ruleForm')">立即修改</el-button>
              <el-button v-else type="success" @click="submitForm('ruleForm')">立即添加</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import {
  getCateList,
  getSecondCateList,
  getSpecsListOption,
  getSpecsAttr
} from "../../request";
import E from "wangeditor";
export default {
  data() {
    return {
      ruleForm: this.transData,
      // 富文本编辑器对象
      editor: null,
      firstCateList: [],
      secondCateList: [],
      // 上传文件列表
      fileList: [],
      // 规格属性ID
      goodSpec: [],
      // 规格属性值
      goodSpecAttr: [],
      activeName: "first",
      rules: {
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "blur" }
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "blur" }
        ],
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" }
        ],
        sepcsid: [
          { required: true, message: "请选择商品规格", trigger: "blur" }
        ],
        sepcsattr: [
          { required: true, message: "请选择规格属性值", trigger: "blur" }
        ]
      }
    };
  },
  props: ["transData", "popType"],
  created() {
    // 获取一级分类下拉菜单中的数据
    this.getFirstData();
    // 获取二级分类的数据
    this.getSecondData(this.ruleForm.first_cateid);
    // 获取规格属性ID
    this.getSpecsList();
    if (this.popType == "修改") {
      this.getSpecsAttrOption(this.ruleForm.specsid);
    }
    if (this.transData.img) {
      this.fileList = [
        {
          name: this.ruleForm.goodsname,
          url: "http://localhost:3000" + this.transData.img
        }
      ];
    } else {
      this.fileList = [];
    }
  },
  mounted() {
    // 在editor这个div中创建编辑器
    this.editor = new E("#editor");
    this.editor.create();
    // 编辑器赋值
    this.editor.txt.html();
    // 获取编辑器的值editor.txt.html();
  },
  watch: {
    transData: {
      handler(newVal, oldVal) {
        if (this.popType == "修改") {
          this.getSpecsAttrOption(newVal.specsid);
        }
        this.getSecondData(newVal.first_cateid);
        if (newVal.img) {
          if (typeof newVal.img == "string") {
            this.fileList = [
              {
                name: newVal.goodsname,
                url: "http://localhost:3000" + this.transData.img
              }
            ];
          }
        } else {
          this.fileList = [];
        }
        this.ruleForm = newVal;
      },
      deep: true
    },
    popType: {
      handler(newVal, oldVal) {
        this.popType = newVal;
      }
    }
  },
  methods: {
    // 获取一级分类数据
    async getFirstData() {
      let res = await getCateList();
      this.firstCateList = res;
    },
    // 获取二级分类
    async getSecondData(id) {
      let res = await getSecondCateList(id);
      this.secondCateList = res;
    },
    // 根据ID获取规格属性
    async getSpecsAttrOption(id) {
      let res = await getSpecsAttr(id);
      this.goodSpecAttr = res[0].attrs;
    },
    getDataById(uid) {
      this.$http.get("/userinfo", { params: { uid } }).then(res => {
        this.ruleForm = res.data.list;
      });
    },
    async getSpecsList() {
      let res = await getSpecsListOption();
      this.goodSpec = res;
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // // 校验成功
          this.ruleForm.specsattr = this.ruleForm.specsattr.join(",");
          // 声明一个formData类型的数据
          let formData = new FormData();
          for (let key in this.ruleForm) {
            formData.append(key, this.ruleForm[key]);
          }
          if (this.popType == "修改") {
            //修改
            this.$http
              .post("/goodsedit", formData)
              .then(res => {
                this.$router.go(0);
              })
              .catch(err => {
                console.log(err);
              });
          } else {
            // 新增
            this.$http
              .post("/goodsadd", formData)
              .then(res => {
                this.$router.go(0);
                console.log(res);
              })
              .catch(err => {
                console.log(err);
              });
          }
        } else {
          // 检验失败
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 文件上传--修改文件
    handleChange(file, fileList) {
      // 当文件变化时，将最终的值传给img
      this.ruleForm.img = file.raw;
    },
    // 监听一级分类
    async firstChange(val) {
      if (val) {
        this.ruleForm.second_cateid = "";
        // this.secondCateList = await getSecondCateList(val);
        this.firstCateList.forEach(item => {
          if (item.id == this.ruleForm.first_cateid) {
            this.secondCateList = item.children ? item.children : [];
          }
        });
      }
    },
    // 监听商品规格ID
    async specIdChange(val) {
      this.ruleForm.specsattr = [];
      let res = await getSpecsAttr(val);
      this.goodSpecAttr = res[0].attrs;

      // if (val) {
      // this.ruleForm.sepcsattr = "";
      // this.secondCateList = await getSecondCateList(val);
      // this.firstCateList.forEach(item => {
      //   if (item.id == this.ruleForm.first_cateid) {
      //     this.secondCateList = item.children ? item.children : [];
      //   }
      // });
      // }
    },
    // tab切换
    handleClick(tab, event) {
      console.log(tab, event);
    },
    limitImg() {
      this.$message.warning("分类图片最多添加1个");
    }
  }
};
</script>
<style lang="" >
.info {
  width: 100%;
  height: auto;
  background: #fff;
}
.box2 {
  width: auto;
  margin: auto;
}
/* .el-dialog__body {
  padding: 0;
}*/
.el-dialog__footer {
  padding: 0px 20px 10px;
}
.el-dialog__wrapper {
  top: -70px;
}
</style>